<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>编辑借货订单</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        var temporary = Ext.create('Ext.form.field.Hidden', {
          name: 'temporary',
          value: 0
        });
        
        var loanId = Ext.create('Ext.form.field.Hidden', {
          name: 'id'
        });

        var version = Ext.create('Ext.form.field.Hidden', {
          name: 'lock_version'
        });
        
        //备注
        var desc = Ext.create('Ext.form.field.Text', {
          fieldLabel: '备注',
          name: 'description',
          anchor: '100%'
        });
        
        //所有客户
        var toCustomer = Ext.create('Ext.form.ComboBox', {
          store: customerStore,
          fieldLabel: '到客户',
          allowBlank: false,
          blankText: "客户必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'customer_id',
          loadingText: '搜索中...',
          anchor: '100%',
          pageSize: 25,
          minChars: 0
        });

        toCustomer.on('select', function(combo, record, index) {
          linkman.setValue(records[0].get('linkman'));
          phone.setValue(records[0].get('phone'));
          deliveryAddress.setValue(records[0].get('address'));
        });

        var addCustomerButton = Ext.create('Ext.Button', {
          text: '添加客户',
          iconCls: 'addItem',
          scale: 'small',
          handler: onAddCustomerButtonClick
        });

        function onAddCustomerButtonClick(){
          newCustomerWin = Ext.create('Ext.window.Window', {
            layout: 'fit',
            width:618,
            height:300,
            closeAction: 'destroy',
            plain: true,
            modal: true,
            constrain:true,
            //modal: true,
            title: '添加客户',
            autoLoad: {
              url: "/customer/newCustomer",
              scripts: true
            }
          });
          newCustomerWin.resizable = false;
          newCustomerWin.show();
        }

        //要求发货时间
        var actionDate = Ext.create('Ext.form.field.Date', {
          fieldLabel: '发货日期',
          name: 'action_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          allowBlank: false,
          blankText: "发货日期必须选择",
          emptyText: '发货日期...',
          anchor: '95%'
        });
        
        //合同号
        var contractNumber = Ext.create('Ext.form.field.Text', {
          fieldLabel: '合同编号',
          allowBlank: true,
          name: 'contract_number',
          anchor: '95%'
        });

        //联系人
        var linkman = Ext.create('Ext.form.field.Text', {
          fieldLabel: '联系人',
          name: 'linkman',
          allowBlank: false,
          anchor: '95%'
        });
        
        //联系电话
        var phone = Ext.create('Ext.form.field.Text', {
          fieldLabel: '联系电话',
          name: 'phone',
          allowBlank: false,
          anchor: '95%'
        });

        var deliveryAddress = Ext.create('Ext.form.field.Text', {
          fieldLabel: '送货地址',
          allowBlank: false,
          name: 'delivery_address',
          anchor: '97%'
        });

        var sales = Ext.create('Ext.form.ComboBox', {
          store: employeeStore,
          fieldLabel: '借货员',
          allowBlank: false,
          blankText: "借货员必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'sales_id',          
          loadingText: '搜索中...',
          anchor: '95%',
          //pageSize: 10,
          
          minChars: 0,          
          anchor: '95%'
        });
        
        var productCBB = Ext.create('Ext.form.ComboBox', {
          store: productAllInfoStore,
          emptyText: '请选择...',
          displayField: 'name',
          loadingText: '搜索中...',
          anchor: '100%',
          minChars: 0,
          listConfig: {
            loadingText: 'Searching...',
            getInnerTpl: function() {
              return '<div style="float:left; width:200px" data-qtip="{name}">{name:ellipsis(18)}</div><div style="float:left; width:110px">{number}</div>{is_suit}';
            }
          },
          pageSize: 10
        });


        productCBB.on('select', function(combo, record, index) {
          var records = loanDetailGrid.getSelectionModel().getSelection();
          var loanItemRecord = records[0];
          if (!loanItemRecord) {
            return false;
          }

          if (isDuplicateByProduct(loanDetailDS,record[0].get('id'),loanItemRecord.id)){
            //删除当前记录
            if (loanItemRecord.get('product_id') != record[0].get('id')){
              loanDetailDS.remove(loanItemRecord);
            }
          }else{
            if (loanItemRecord.get('product_id') != record[0].get('id')){
              loanItemRecord.set('number',record[0].get('number'));
              loanItemRecord.set('spec',record[0].get('spec'));
              loanItemRecord.set('unit',record[0].get('unit'));
              loanItemRecord.set('quantity',1);
              loanItemRecord.set('product_id',record[0].get('id'));
              //判断套装
              loanItemRecord.set('is_suit',record[0].get('is_suit'));
            }
          }
        });

        //借货订单列表Grid Store
        var loanDetailDS = Ext.create('Ext.data.Store', {
          autoDestroy : true,
          model : 'LoanOrderDetailEditModel',
          proxy : {
            type : 'ajax',
            url : '/loan/getLoanDetailsById',
            extraParams:{'loan_id' : <%=params[:id]%>},
            reader : {
              type : 'json',
              root : 'root',
              totalProperty : 'totalProperty'// 数据集记录总数
            }
          },
          autoLoad : true
        });

        //生成要订单的产品的Grid
        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
          clicksToEdit: 1
        });
        
        var loanDetailGrid = Ext.create('Ext.grid.Panel', {
          store: loanDetailDS,
          plugins: [cellEditing],
          columns : [Ext.create('Ext.grid.RowNumberer'),{
              header: '产品名称',
              dataIndex: 'product_name',
              field: productCBB,
              width: 370
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden: false
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 90
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 40
            },{
              header: '数量',
              align: 'right',
              dataIndex: 'quantity',
              field: Ext.create('Ext.form.field.Number', {
                allowBlank: false,
                allowDecimals: false,
                minValue: 1
              }),
              width: 50
            },{
              header: '套装或单品',
              dataIndex: 'is_suit',
              width: 70
            },{
              header: '备注',
              dataIndex: 'description',
              width: 230,
              field:Ext.create('Ext.form.field.Text', {
                name: 'description',
                anchor: '95%'
              })
            }],
          selModel :Ext.create('Ext.selection.CheckboxModel'),
          width: 1040,
          height: 300,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,          
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              handler : function(){
                var record = Ext.ModelManager.create({
                  product_name: '请选择产品'
                }, loanDetailGrid.getStore().model);
                loanDetailDS.insert(0, record);                
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var records = loanDetailGrid.getSelectionModel().getSelection();
                cellEditing.cancelEdit();
                loanDetailDS.remove(records);
              }
            }]
        });

        //提交
        var submitButton = Ext.create('Ext.Button', {
          text: '提交',
          tooltip: '提交借货订单。',
          iconCls: 'icon-save',
          handler: function(){
            if (sales.getRawValue() === sales.getValue()){
              sales.reset();
            }

            if (toCustomer.getRawValue() === toCustomer.getValue()){
              toCustomer.reset();
            }
            
            if (loanFormPanel.form.isValid()){
              var productsJsonStr = gridStoreToJson(loanDetailDS,rejectKeyArray);
              if (loanDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              this.disable();
              var allJsonStr = loanFormPanel.getForm().getValues();
              allJsonStr = Ext.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              //alert(allJsonStr);
              Ext.Ajax.request({
                url : '/loan/update',
                success : function (result, request) {
                  if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "保存借货订单，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                  }
                  else {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: Ext.JSON.decode(result.responseText).info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  }
                  editLoanWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请联系管理员！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  editLoanWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });

        //临时保存按钮
        var tempSaveButton = Ext.create('Ext.Button', {
          text: '暂存',
          tooltip: '暂时保存借货订单。',
          iconCls: 'temp-save',
          handler: function(){
            //首先把临时变量设置为1
            temporary.setValue(1);
            if (sales.getRawValue() === sales.getValue()){
              sales.reset();
            }

            if (toCustomer.getRawValue() === toCustomer.getValue()){
              toCustomer.reset();
            }

            if (loanFormPanel.form.isValid()){

              var productsJsonStr = gridStoreToJson(loanDetailDS,rejectKeyArray);
              if (loanDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              //没有添加产品，则提示
              if (loanDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              this.disable();
              var allJsonStr = loanFormPanel.getForm().getValues();
              allJsonStr = Ext.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              //alert(allJsonStr);
              Ext.Ajax.request({
                url : '/loan/update',
                success : function (result, request) {
                  if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "保存借货订单，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                  }
                  else {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: Ext.JSON.decode(result.responseText).info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  }
                  editLoanWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请联系管理员！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  editLoanWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });
        
        //暂时保存按钮
        var closeButton = Ext.create('Ext.Button', {
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            editLoanWin.destroy();
          }
        });
        
        //采购申请的FormPanel
        var loanFormPanel = Ext.create('Ext.form.Panel', {
          fieldDefaults: {
            labelWidth: 55,
            labelAlign: 'right'
          },
          width: '1050',
          frame : true,
          url: '/loan/update',
          method: 'GET',
          reader: Ext.create('Ext.data.reader.Json',{
            model: 'LoanOrderModel',
            root: 'root'
          }),
          //defaultType: 'textfield',
          items: [{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .6,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [toCustomer]
                }, {
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [addCustomerButton]
                }, {
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [contractNumber]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [linkman]
                }, {
                  columnWidth: .4,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [phone]
                }, {
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [actionDate]
                }, {
                  columnWidth: .2,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [sales]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [deliveryAddress]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [desc]
                }]
            },{
              layout: 'column',
              xtype: 'container',
              items: [{
                  columnWidth: 1,
                  layout: 'anchor',
                  xtype: 'container',
                  items: [loanDetailGrid]
                }]
            },temporary,loanId,version],
          buttons: [submitButton,tempSaveButton,closeButton]
        });


        loanFormPanel.form.load({
          url: '/loan/getLoanById?id=' + <%=params[:id]%>,
          method : 'GET',
          waitMsg: '正在载入数据...',
          success: function(form, action){
          },
          failure: function(form, action){
            Ext.MessageBox.show({
              title: '消息',
              msg: "信息加载失败！",
              buttons: Ext.MessageBox.OK,
              icon: Ext.MessageBox.WARNING
            });
            editLoanWin.destroy();
          }
        });

        loanFormPanel.render('edit_loan');
      })
    </script>
  </head>
  <body>
    <div id="edit_loan"></div>
  </body>
</html>